package com.ruoyi.system.utils;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.utils.IOUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhubayi
 * 七牛云工具类
 */
@Slf4j
public class PANGXIEAliUtils {


    public ResponseEntity<String> uploadFile(MultipartFile file) throws Exception {
        // 获取文件内容
        byte[] fileBytes = file.getBytes();


//        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("bizCode", "product");
        headers.add("sceneCode", "account");

        // 调用外部API获取STS token
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.exchange("https://www.pxb7.com/api/common/file/stsToken/v2" +
                "?bizCode=product&sceneCode=account", HttpMethod.GET, new HttpEntity<>(headers), Map.class);
        Map<String, String> data = response.getBody();
        System.out.println(data);

        String body1 = HttpRequest.get("https://www.pxb7.com/api/common/file/stsToken/v2?bizCode=product&sceneCode" +
                "=account").execute().body();
        System.out.println(body1);

        String ciphertext = "";
        String iv = "";


        // 解密数据
        String decryptedData = decryptData(data.get("ciphertext"), data.get("iv"));

        // 构建上传参数
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("x-oss-signature-version", data.get("version"));
        body.add("x-oss-credential", data.get("credential"));
        body.add("x-oss-date", data.get("date"));
        body.add("x-oss-signature", data.get("signature"));
        body.add("success_action_status", "200");
        body.add("x-oss-forbid-overwrite", "true");
        body.add("policy", data.get("policy"));
        body.add("x-oss-security-token", data.get("token"));
        body.add("key", "your/path/to/file");
        body.add("file", fileBytes);

        // 上传文件
        HttpHeaders headers2 = new HttpHeaders();
        headers2.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers2);
        ResponseEntity<String> uploadResponse = restTemplate.postForEntity("https://public-image.pxb7.com/",
                requestEntity, String.class);

        return ResponseEntity.ok(uploadResponse.getBody());
    }

    private static String decryptData(String ciphertext, String iv) throws GeneralSecurityException {
        byte[] keyBytes = org.apache.commons.codec.binary.Base64.decodeBase64("A2M0ebV5eN9wON5K2-zvbvOnT_qMyTDW8XSurv3lj5w=");
        byte[] ivBytes = org.apache.commons.codec.binary.Base64.decodeBase64(iv);
        byte[] cipherTextBytes = org.apache.commons.codec.binary.Base64.decodeBase64(ciphertext);

        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, ivBytes); // 128 bit auth tag length

        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec);
        byte[] plainTextBytes = cipher.doFinal(cipherTextBytes);

        return new String(plainTextBytes, StandardCharsets.UTF_8);
    }

    static String getBody(String token) {
        String attrUrl = "https://www.pxb7.com/api/common/file/stsToken/v2?bizCode=product&sceneCode=account";
        String body = HttpRequest.get(attrUrl)
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Connection", "keep-alive")
                .header("client_type", "client_type")
                .header("px-authorization-merchant", token)
                .header("px-authorization-user", token)
                .header("sec-ch-ua", "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"")
                .header("sec-ch-ua-mobile", "a7228a7d885a3f09046ee2a8fb2e3252")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .execute().body();
        return body;
    }
    public static String upLoadImg(JSONObject data, String img) {
        byte[] bytes = THHAliUtils.downloadPicture(img);
        String name = img.substring(img.lastIndexOf("."));
//        MultipartFile multipartFile = THHAliUtils.getMultipartFile(name, bytes);
        File file = null;
        try {
            file = convert(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String attrUrl = "https://public-image.pxb7.com/";

        //        https://public-image.pxb7.com/pxb7-upload/product/account/20241214/1734154740705.jpg
        String path = data.getString("k") + "/" + System.currentTimeMillis() + ".jpg";

        Map<String, Object> herder = new HashMap<>();
        herder.put("Accept", "*/*");
        herder.put("Accept-Language", "zh-CN,zh;q=0.9");
        herder.put("Connection", "keep-alive");
        herder.put("Origin", "https://www.pxb7.com");
        herder.put("Referer", "https://www.pxb7.com/");
        herder.put("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryLYlwBhY2BVrkll0O");

//
//        Map<String, Object> params = new HashMap<>();
//        params.put("x-oss-signature-version", data.get("v"));
//        params.put("x-oss-credential", data.get("c"));
//        params.put("x-oss-date", data.get("a"));
//        params.put("x-oss-signature", data.get("s"));
//        params.put("success_action_status", "200");
//        params.put("x-oss-forbid-overwrite", "true");
//        params.put("policy", data.get("p"));
//        params.put("x-oss-security-token", data.get("t"));
//        params.put("key", path);
//        params.put("file", file);

//        String s = HttpUtils.doPostFormData(attrUrl, params, herder);

        String s = HttpRequest.post(attrUrl)
                .form("x-oss-signature-version", data.get("v"))
                .form("x-oss-credential", data.get("c"))
                .form("x-oss-date", data.get("a"))
                .form("x-oss-signature", data.get("s"))
                .form("success_action_status", "200")
                .form("x-oss-forbid-overwrite", "true")
                .form("policy", data.get("p"))
                .form("x-oss-security-token", data.get("t"))
                .form("key", path)
                .form("file", file)
                .header("Referer", "https://www.pxb7.com/")
                .header("Origin", "https://www.pxb7.com")
                .header("Content-Type", "multipart/form-data; boundary=<calculated when request is sent>")
                .execute().body();
//        System.out.println(s);
//        System.out.println(data.getString("m") + "/" + path);
        return data.getString("m") + "/" + path;
    }

    public static File convert(byte[] byteArray) throws IOException {
        File file = File.createTempFile("pangxie", ".jpg");
//        imgUrl = file.getPath();
        Path path = Paths.get(file.getAbsolutePath());
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(byteArray);
        }catch (Exception e){

        }
        return file;
    }

    public static byte[] downloadPicture(String url) {
        URL urlConnection = null;
        HttpURLConnection httpURLConnection = null;
        try {
            urlConnection = new URL(url);
            httpURLConnection = (HttpURLConnection) urlConnection.openConnection();
            InputStream in = httpURLConnection.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            in.close();
            out.close();
            return out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpURLConnection.disconnect();
        }
        return null;
    }

    //二进制文件转换MultipartFile
    public static MultipartFile getMultipartFile(String name, byte[] bytes) {
        MultipartFile mfile = null;
        ByteArrayInputStream in = null;
        try {
            in = new ByteArrayInputStream(bytes);
            FileItemFactory factory = new DiskFileItemFactory(16, null);
            FileItem fileItem = factory.createItem("mainFile", "text/plain", false, name);
            IOUtils.copy(new ByteArrayInputStream(bytes), fileItem.getOutputStream());
            mfile = new CommonsMultipartFile(fileItem);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mfile;
    }
}

